//
//  AllTableViewController.swift
//  osc
//
//  Created by admin on 14/10/28.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import UIKit



let CELL_ALL = "TITLE_SUBTITLE"
class AllTableViewController: UITableViewController {
    
    var datasource = NewsList()
    var segment: UISegmentedControl?
    var catalog: Int = 1
    var pageIndex: Int = 1
    var classification: [String] = ["综合","软件更新","所有"]

    
    override func viewWillAppear(animated: Bool) {
        self.tabBarController?.tabBar.hidden = false
    }
    
    
    override func viewDidLoad() {
        self.tabBarController?.tabBar.hidden = false
        super.viewDidLoad()
        // Uncomment the following line to preserve selection between presentations
        self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        setSegment()

        //var app = UIApplication.sharedApplication().delegate as AppDelegate
        var token: Tokencc? = app.token
        println("------token=\(token)")
        if token != nil{
            println(" token.expires_inffff = \(token!.expires_in)")
            
            println(" token.is_onlinefffff = \(token!.is_online)")
            println(" token.date_createdfffff = \(token!.date_created)")
        }
        

        var parameters = ["access_token":access_token ,"catalog":self.catalog, "page/pageIndex":1, "pageSize":20, "dataType": "json"]
        HttpClient.loadData(api_news_list, parameters: parameters, success: { () -> Void in
            self.tableView.reloadData()
            }, phaser: {(data)-> Void in

                self.datasource.append(NewsList(JSONDecoder(data)).newslist)
        })
        self.tableView.scrollsToTop = true
        setFreshControl()
        
    }
    
    
    func setFreshControl(){
        var refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新")
        self.refreshControl = refreshControl
        self.refreshControl?.addTarget(self, action: "frechControlValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    func frechControlValueChanged(sender: AnyObject){
        self.refreshControl?.beginRefreshing()
        var parameters = ["access_token":access_token ,"catalog":self.catalog, "page/pageIndex":1, "pageSize":20, "dataType": "json"]
        HttpClient.loadData(api_news_list, parameters: parameters, success: { () -> Void in
            self.tableView.reloadData()
            }, phaser: {(data)-> Void in
                self.datasource.append(NewsList(JSONDecoder(data)).newslist)
        })
        
        
        self.refreshControl?.endRefreshing()
    }
    
    func setSegment(){
        segment = UISegmentedControl(items: classification)
        segment?.addTarget(self, action: "segmentValueChange:", forControlEvents: UIControlEvents.ValueChanged)
        segment?.selectedSegmentIndex = 0
        self.navigationItem.titleView = segment
    }
    
    func segmentValueChange(sender: AnyObject){
        self.pageIndex = 1
        self.catalog = self.segment!.selectedSegmentIndex + 1
        var parameters = ["access_token":access_token ,"catalog":self.catalog, "page/pageIndex":1, "pageSize":20, "dataType": "json"]
        self.datasource.newslist.removeAll(keepCapacity: false)
        HttpClient.loadData(api_news_list, parameters: parameters, success: { () -> Void in
            
            self.tableView.reloadData()
            //            self.tableView.scrollRectToVisible(CGRectMake(0, -120, self.tableView.frame.width, self.tableView.frame.height), animated: true)
            }, phaser: {( data )-> Void in
                self.datasource.append(NewsList(JSONDecoder(data)).newslist)
        })
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return self.datasource.count + 1
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(CELL_ALL, forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...
        
        //println("indexPath.row=\(indexPath.row)   datasource.count=\(self.datasource.count)")
        if indexPath.row == self.datasource.count{
            cell.textLabel?.text = "加载更多"
            cell.detailTextLabel?.text = ""
        }else{
            var newsM = self.datasource.newslist[indexPath.row]
            var newsMV = NewsMV(news: newsM)
            cell.textLabel?.text = newsMV.news_title
            cell.detailTextLabel?.text = newsMV.sub_title
        }

        return cell
    }


    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        if indexPath.row == self.datasource.count{
            pageIndex += 1
            var parameters = ["access_token":access_token ,"catalog":self.catalog, "page/pageIndex":pageIndex, "pageSize":20, "dataType": "json"]
            HttpClient.loadData(api_news_list, parameters: parameters, success: { () -> Void in
                self.tableView.reloadData()
                }, phaser: {(data)-> Void in
                    println()
            })
        }else{
            self.performSegueWithIdentifier("new_detail", sender: tableView)
        }
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        var target = segue.destinationViewController as UIViewController
        target.title = self.classification[self.catalog-1]
        
        var indexPath = (sender as UITableView).indexPathForSelectedRow()
        
        var id = self.datasource.newslist[indexPath!.row].id
        
        target.setValue(id, forKey: "id")
    }


}
